package script;

import com.zh.freechat.common.req.ChatUserForm;
import com.zh.freechat.domain.user.entity.ChatUser;
import com.zh.freechat.domain.user.repository.UserRepository;
import com.zh.freechat.domain.user.service.ChatUserService;
import com.zh.mycommon.value.Tuple2;
import com.zh.webcommon.common.support.SpringContextHolder;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static com.zh.freechat.domain.user.UserStatus.USER_ACTIVE;
import static com.zh.freechat.domain.user.entity.ChatUser.SECRET;
import static com.zh.freechat.domain.user.entity.ChatUser.UID_PREFIX;
import static com.zh.mycommon.util.MyCommonUtil.base64Encode;

/**
 * 创建账号的脚本
 * @author Zhou
 * @date 14:45 2024/12/26
 */
public class RegisterUserScript {

    static void register(List<Tuple2<String, String>> tuples) {
        var userService = SpringContextHolder.getBean(ChatUserService.class);

        var defaultPasswd = base64Encode("123456");
        for (Tuple2<String, String> tuple : tuples) {
            ChatUserForm form = new ChatUserForm();
            form.setUsername(tuple.v1());
            form.setNickname(tuple.v2());
            form.setEmail(tuple.v1() + "@qq.com");
            form.setPassword(defaultPasswd);
            form.setCode("000000");

            try {
                String uid = userService.addUser(form);
                userService.activeUser(uid);
            } catch (Exception ex) {
                System.out.println(form.getUsername() + " 注册失败. " + ex.getMessage());
            }
        }
    }

    static int autoId = 1;


    public void GenerateRegisterRobots() {
        List<Tuple2<String, String>> tuples = new ArrayList<>(360);
        for (int i = 1; i <= 360; i++) {
            // 格式化数字为三位数：001, 002, ..., 360
            String numStr = String.format("m%03d", i);
            String degreeStr = i + "°度";
            tuples.add(new Tuple2<>(numStr, degreeStr));
        }
        registerRobot(tuples);
    }

    static void registerRobot(List<Tuple2<String, String>> tuples) {
        var userRepository = SpringContextHolder.getBean(UserRepository.class);

        for (Tuple2<String, String> tuple : tuples) {
            try {
                ChatUser user = new ChatUser();
                user.setIsRobot(true);
                user.setRole("USER");
                user.setGender(SECRET);
                user.setStatus(USER_ACTIVE.getCode());
                user.setCreateTime(LocalDateTime.now());
                user.setAvatarUrl("https://picsum.photos/300?random="+autoId);
                user.setUid(UID_PREFIX + (autoId));
                user.setUsername(tuple.v1());
                user.setNickname(tuple.v2());

                userRepository.insert(user);
                autoId++;
            } catch (Exception ex) {
                System.out.println(tuple.v1() + " 注册失败. " + ex.getMessage());
            }
        }
    }

}
